package com.example.demo;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author: wuhong-016
 * @time: 2021/4/9 14:28
 * @version: v1.0.0
 * @description:TODO
 */
public class TxtUtil {

    public static List<String> readTxtByPage(String filePath, int currentPage, int pageSize) throws IOException, FileNotFoundException {
        File sourceFile = new File(filePath);
        if (null == sourceFile || !sourceFile.isFile()) {
            throw new RuntimeException("目标文件不存在");
        }
        List<String> list = new ArrayList<>(1000);

        FileReader in = null;
        LineNumberReader reader = null;
        try {
            in = new FileReader(sourceFile);
            reader = new LineNumberReader(in);
            //第一行是标题，不读
            int startRow = (currentPage - 1) * pageSize;
            int endRow = currentPage * pageSize;
            int lines;
            System.out.println("startRow:" + startRow);
            System.out.println("endRow:" + endRow);
            String rowStr = "";
            while (rowStr != null) {
                lines = reader.getLineNumber();
                rowStr = reader.readLine();
                if (lines < startRow) {
                    //do nothing
                } else if (lines >= startRow && lines < endRow) {
                    list.add(rowStr);
                    System.out.println(reader.getLineNumber() + " : " + rowStr);
                } else {
                    return list;
                }
            }
            System.out.println("----------- list size:" + list.size() + "-----" + list);
        } finally {
            if (null != in) {
                in.close();
            }
            if (null != reader) {
                reader.close();
            }
        }
        return list;

    }

}
